"""
文件存储查询参数模型
"""
from typing import Optional
from fastapi import Query
from axiom_boot.api.filter_params import BaseFilterParams, FilterOperator

class StorageFilterParams(BaseFilterParams):
    """
    用于文件/文件夹列表查询的过滤参数模型
    """
    bucket: str = Query(..., description="存储桶名称")
    parent_id: Optional[str] = Query(None, description="父文件夹ID，不传则为根目录")
    name: Optional[str] = Query(None, description="要模糊搜索的文件或文件夹名称") 
    is_dir: Optional[int] = Query(None, description="是否为文件夹 (0: 否, 1: 是)")

    _operators = {
        "name": FilterOperator.LIKE,
        "parent_id": FilterOperator.IS, # 父ID为None时，使用 IS NULL
    }
    
    def to_filter_dict(self):
        data = self.model_dump(exclude_unset=True)

        # [关键修复] 将 ID 从 str 转换回 int 以进行数据库查询
        if 'parent_id' in data and data['parent_id'] is not None:
            data['parent_id'] = int(data['parent_id'])

        filter_dict = {}
        for field, value in data.items():
            operator = self._operators.get(field, FilterOperator.EQUAL)
            
            # 特殊处理 parent_id 为 None 的情况
            if field == 'parent_id' and value is None:
                operator = FilterOperator.IS
            
            key = f"{field}__{operator.value}"
            
            if operator == FilterOperator.LIKE and value is not None:
                filter_dict[key] = f"%{value}%"
            else:
                filter_dict[key] = value
        
        return filter_dict
